package cn.cj.erp.common.utils.id;

import cn.cj.erp.common.utils.SpringUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 雪花算法创建Bean: uuid主键生成器, 利用twitter开源的snowflake算法
 * @author jianchen
 */
@Configuration
public class IdGenerator {

    @Value("${spring.cloud.client.ip-address:127.0.0.1}")
    private String ip;

    @Value("${server.port:8080}")
    private int port;

    @Bean
    public SnowflakeIdWorker snowflakeIdWorker() {
        // 服务器ID
        long workerId;
        // 中心ID
        long datacenterId;
        // 临时变量
        int h;

        long workerIdHashCode = StrUtil.isEmpty(ip) ? 0L : (h = ip.hashCode()) ^ (h >>> 16);
        long datacenterIdHashCode = port;
        workerId = 31 & workerIdHashCode;
        datacenterId = 31 & datacenterIdHashCode;
        return new SnowflakeIdWorker(workerId, datacenterId);
    }

    /**
     * 生成ID
     * @return id
     */
    public static Long generateId() {
        // 获取雪花算法Bean
        SnowflakeIdWorker snowflakeIdWorker = SpringUtil.getBean(SnowflakeIdWorker.class);
        return snowflakeIdWorker.generateId();
    }
}
